<template>
  <div class="energy_consume">
    <div v-if="showDetails" class="top_turnback">
      <px-button type="primary" :icon="ArrowLeft" @click="showDetails = !showDetails">返回</px-button>
    </div>
    <div class="top_query">
      <px-radio-group v-model="queryTimeType" style="margin-right: 80px" @change="handleChange">
        <px-radio-button label="DAY">本日</px-radio-button>
        <px-radio-button label="MONTH">本月</px-radio-button>
        <px-radio-button label="YEAR">本年</px-radio-button>
      </px-radio-group>
      <px-form ref="queryRef" :model="queryParams" :inline="true" label-width="90px">
        <px-form-item label="时间粒度" prop="dataFormat">
          <px-radio-group v-model="queryParams.queryTimeGranularity" @change="handleChangeFn">
            <px-radio-button label="DAY">日</px-radio-button>
            <px-radio-button label="MONTH">月</px-radio-button>
            <px-radio-button label="YEAR">年</px-radio-button>
          </px-radio-group>
        </px-form-item>
        <px-form-item label="时间范围" style="width: 520px">
          <px-date-picker
            v-if="queryParams.queryTimeGranularity === 'MONTH'"
            v-model="dateRange"
            value-format="YYYY-MM"
            type="monthrange"
            range-separator="-"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
          />
          <div v-else-if="queryParams.queryTimeGranularity === 'YEAR'" class="select_year">
            <px-date-picker v-model="queryParams.startTime" value-format="YYYY" type="year" placeholder="开始年份" />
            <span>&nbsp;-&nbsp;</span>
            <px-date-picker v-model="queryParams.endTime" value-format="YYYY" type="year" placeholder="结束年份" />
          </div>
          <px-date-picker
            v-else
            v-model="dateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </px-form-item>
        <px-form-item>
          <px-button type="primary" icon="" @click="handleQuery">搜索</px-button>
          <px-button icon="" @click="resetQuery">重置</px-button>
        </px-form-item>
      </px-form>
    </div>
    <topDiv
      v-if="!showDetails"
      :key="midKey + 10"
      class="con_top"
      :width="350"
      :height="360"
      :isSerch="isSerch"
      :energyType="activeName"
      :className="routerStore.subject"
      :queryTimeType="queryTimeType"
      :queryParams="queryParams"
      :dateRange="dateRange"
      :energyTitle="energyTitle"
      :dict-key-list="JSON_DATA[`${routerStore.subject}_${activeName}_TOP`]"
    />
    <midDiv
      v-if="!showDetails"
      :key="midKey"
      :isSerch="isSerch"
      :energyType="activeName"
      :className="routerStore.subject"
      :queryTimeType="queryTimeType"
      :dateRange="dateRange"
      :queryParams="queryParams"
      :energyTitle="energyTitle"
      :dict-key-list="JSON_DATA[`${routerStore.subject}_${activeName}_MID`]"
    />
    <bottomDiv
      :key="midKey + 100"
      class="con_bot"
      :showDetails="showDetails"
      :isSerch="isSerch"
      :energyType="activeName"
      :className="routerStore.subject"
      :queryTimeType="queryTimeType"
      :dateRange="dateRange"
      :queryParams="queryParams"
      :energyTitle="energyTitle"
      :dict-key-list="JSON_DATA[`${routerStore.subject}_${activeName}_BOTTOM`]"
      @btn-click="handleBtnClick"
    />
  </div>
</template>
<script setup lang="ts">
import { ref, getCurrentInstance, onMounted, nextTick, computed, onUnmounted } from "vue";
import jsonData from "@/views/common/energy/components/energyConsumePageDict.json";
import { useRouterStoreHook } from "@/store/modules/router";
import type { UtilsEChartsOption } from "@pureadmin/utils";
import { ArrowLeft } from "@px-ui/icons-vue";
import * as energyModel from "@/api/modules/energy";
import { emitter } from "@/utils/mitt";
import topDiv from "../components/top.vue";
import midDiv from "../components/mid.vue";
import bottomDiv from "../components/bottom.vue";
import { PxMessage } from "px-ui";
const { proxy }: any = getCurrentInstance();
const activeName = ref("ELECTRICTITY"); // 默认电
emitter.on("viceMenuChange", (val: string) => {
  activeName.value = val;
  midKey.value = Date.now();
});

const midKey = ref(Date.now());

const showDetails = ref<boolean>(false);

const handleBtnClick = () => {
  showDetails.value = true;
};

const JSON_DATA = ref<any>(jsonData);

onMounted(() => {
  nextTick(() => {});
  console.log(jsonData);
});
onUnmounted(() => {
  emitter.off("viceMenuChange");
});
const routerStore = useRouterStoreHook();
const energyTitle = computed(() => {
  switch (activeName.value) {
    case "HOT_WATER":
      return "水";
      break;
    case "HOT_STEAM":
      return "蒸汽";
      break;
    case "NG":
      return "LNG";
      break;
    case "ELECTRICTITY":
      return "电";
      break;
    case "HOT_WATER_NEW":
      return "热水";
      break;
    case "CDA":
      return "CDA";
      break;
    default:
      return "";
      break;
  }
});
const dateTitle = computed(() => {
  switch (activeName.value) {
    case "DAY":
      return "日";
      break;
    case "MONTH":
      return "月";
      break;
    case "YEAR":
      return "年";
    default:
      return "";
      break;
  }
});

type itemStyleType = {
  [key: string]: string;
};

interface dataType {
  name: string;
  value: number;
  itemStyle?: itemStyleType;
}

const isWater = ref<Boolean>(false);
// 总排名
const labelLayoutAreaFn1 = async (ec: any) => {
  const title = "总排名";
  const param = {
    className: routerStore.subject === "ALL" ? "" : routerStore.subject,
    energyType: activeName.value
  };
  const res: any = await energyModel.eqttablelListAll(param);
  const data = res.equipmentRankingList.map(item => {
    const { consume_amount: value, eqp_1st_category_name: name } = item;
    return { value, name };
  });
  return labelLayoutFn1(ec, data, title);
};

const labelLayoutFn1 = (ec: any, data: Array<dataType>, title: string) => {
  const { getWidth } = ec;
  // labelLine长度
  const labelLayout = function (params) {
    const isLeft = params.labelRect.x < getWidth() / 2;
    const points = params.labelLinePoints;
    points[2][0] = isLeft ? params.labelRect.x : params.labelRect.x + params.labelRect.width;
    return { labelLinePoints: points };
  };
  const options: UtilsEChartsOption = {
    color: ["#5B8FF9", "#5AD8A6 ", "#FFB910"],
    tooltip: {
      trigger: "axis",
      confine: true,
      axisPointer: {
        type: "cross",
        crossStyle: {
          color: "#999"
        }
      }
    },
    grid: {
      left: "0px",
      top: "40px",
      right: "10px",
      bottom: "10px",
      containLabel: true
    },
    xAxis: [
      {
        type: "category",
        data: [1, 2, 3]
      }
    ],
    yAxis: [
      {
        type: "value"
      }
    ],
    series: [
      {
        name: "属性值",
        type: "line",
        data: [1, 2, 3]
      }
    ]
  };
  return options;
};

const getParams = (selectType: string) => {
  const { subject: className, activeViceMenu: gasName } = routerStore;
  if (className === "GAS") {
    return { className, gasName, selectType };
  } else {
    return { className, selectType };
  }
};

const dateRange = ref([]);

interface queryForm {
  queryTimeGranularity?: string;
  startTime?: string;
  endTime?: string;
}

const queryParams = ref<queryForm>({
  queryTimeGranularity: ""
});
const queryTimeType = ref("DAY");

const loading = ref(false);
const handleChange = (val: string) => {
  queryParams.value.queryTimeGranularity = "";
  queryTimeType.value = val;
  dateRange.value = [];
  queryParams.value.startTime = "";
  queryParams.value.endTime = "";
  if (val) midKey.value = Date.now();
};
const handleChangeFn = (val: string) => {
  queryTimeType.value = "";
  queryParams.value.queryTimeGranularity = val;
  dateRange.value = [];
  queryParams.value.startTime = "";
  queryParams.value.endTime = "";
};

// 校验时间范围不为空
const checkDate = () => {
  if (queryParams.value.queryTimeGranularity) {
    if (dateRange.value && dateRange.value.length) {
      return true;
    }
    if (queryParams.value.startTime && queryParams.value.endTime) {
      return true;
    }
  }
};

const isSerch = ref(false);
/** 搜索按钮操作 */
function handleQuery() {
  proxy.$refs["queryRef"].validate(valid => {
    if (!valid) return;
    if (queryParams.value.queryTimeGranularity) {
      if (!checkDate()) {
        return PxMessage({
          type: "warning",
          message: "时间范围不能为空"
        });
      }
      midKey.value = Date.now();
      isSerch.value = !isSerch.value;
    } else {
      midKey.value = Date.now();
      isSerch.value = !isSerch.value;
    }
  });
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  dateRange.value = [];
  queryParams.value.queryTimeGranularity = "";
  queryParams.value.startTime = "";
  queryParams.value.endTime = "";
  queryTimeType.value = "DAY";
  handleQuery();
}

// 反转数组
const reverseArray = (arr: any[]) => {
  let newArr = [];
  arr.forEach((item: any) => {
    newArr.unshift(item);
  });
  return newArr;
};
</script>

<style lang="scss" scoped>
.energy_consume {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;

  .top_turnback {
    margin-bottom: 16px;
  }

  .top_query {
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
    justify-content: left;
    width: 100%;
    min-width: 1300px;
    height: auto;
    padding: 16px 24px;
    margin-bottom: 16px;
    line-height: 44px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 10px 0 rgb(0 37 86 / 12%);

    .select_year {
      display: flex;
      align-items: center;
      justify-content: left;
      margin-right: 20px;
    }

    .px-form-item {
      margin-bottom: 0;
    }
  }

  .con_top {
    display: flex;
    justify-content: space-between;
    width: 100%;
    min-width: 1300px;
    height: 360px;
    margin-bottom: 16px;

    .con_top_item:nth-child(1) {
      width: 33%;
      margin-right: 16px;
    }

    .con_top_item:nth-child(2) {
      width: 67%;
    }
  }

  .con_bot {
    width: 100%;
    min-width: 1300px;
  }
}
</style>
